package com.zl.learning.thread;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierTest {

    public static class CyclicBarrierTest1 {
        static CyclicBarrier c = new CyclicBarrier(2);

        public static void main(String[] args) {
            new Thread(() -> {
                try {
                    c.await();
                } catch (Exception ignored) {

                }
                System.out.println(1);
            }).start();

            try {
                c.await();
            } catch (Exception ignored) {

            }
            System.out.println(2);
        }
    }

    public static class CyclicBarrierTest2 {

        static CyclicBarrier c = new CyclicBarrier(2, new A());

        public static void main(String[] args) {
            new Thread(() -> {
                try {
                    c.await();
                } catch (Exception ignored) {

                }
                System.out.println(1);
            }).start();

            try {
                c.await();
            } catch (Exception ignored) {

            }
            System.out.println(2);
        }

        static class A implements Runnable {

            @Override
            public void run() {
                System.out.println(3);
            }

        }

    }

    public static class CyclicBarrierTest3 {

        static CyclicBarrier c = new CyclicBarrier(2);

        public static void main(String[] args) throws InterruptedException, BrokenBarrierException {
            Thread thread = new Thread(() -> {
                try {
                    c.await();
                } catch (Exception ignored) {
                }
            });
            thread.start();
            thread.interrupt();
            try {
                c.await();
            } catch (Exception e) {
                System.out.println(c.isBroken());
            }
        }
    }

    public static class Test1 {
        public static void main(String[] args) throws BrokenBarrierException, InterruptedException {
            CyclicBarrier cb = new CyclicBarrier(9, () -> System.out.println("龙珠收集完成"));
            for (int i = 0; i < 9; i++) {
                new Thread(() -> {
                    System.out.println(Thread.currentThread().getName() + "号龙珠");
                    try {
                        cb.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (BrokenBarrierException e) {
                        e.printStackTrace();
                    }
                }, String.valueOf(i + 1)).start();
            }
            System.out.println(Thread.currentThread().getName()+"正执行");
        }
    }
}
